<template>
  <div class="calendarHeatmap-container" style="width: 100%; height: 190px">
    <div
      class="calendarHeatmap-title"
      style="display: flex; justify-content: space-between; height: 25px"
    >
      <div
        class="title"
        style="margin-left: 50px; font-size: 18px; font-weight: 700"
      >
        {{ currentYear }}年文章发布数据
      </div>
      <!-- 只能查看近三年的数据，数据存储时效 -->
      <div class="year-select-button" style="margin-right: 50px">
        <el-dropdown trigger="click" @command="handleYearCommand">
          <!-- 展示第一个数据 -->
          <span class="el-dropdown-link" style="cursor: pointer">
            {{ currentYear }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="year in yearList"
              :key="year"
              :command="year"
              :disabled="year === currentYear"
            >
              {{ year }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div id="calendarHeatmap" style="width: 100%; height: 165px"></div>
  </div>
</template>

<script lang="ts">
// 按需引入echarts
import { Component, Vue } from "vue-property-decorator";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TitleComponentOption,
  CalendarComponent,
  CalendarComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  VisualMapComponent,
  VisualMapComponentOption,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import { HeatmapChart, HeatmapSeriesOption } from "echarts/charts";
import { getEveryYearPublish } from "@/apis/apis";
// 注册必须的组件
echarts.use([
  CalendarComponent,
  VisualMapComponent,
  TitleComponent,
  TooltipComponent,
  CanvasRenderer,
  HeatmapChart,
]);
type EChartsOption = echarts.ComposeOption<
  | TitleComponentOption
  | CalendarComponentOption
  | TooltipComponentOption
  | VisualMapComponentOption
  | HeatmapSeriesOption
>;
@Component({
  name: "calendarHeatmap",
})
export default class calendarHeatmap extends Vue {
  // 最早只能在created中掉用，此时data和methods已经初始化
  created() {
    // 获取年份列表,并初始化当前徐那种展示的年份
    this.yearList = this.getYear();
    this.currentYear = this.yearList[0];
    // console.log(this.yearList);
  }
  async mounted() {
    this.initChart();
    this.initData(this.currentYear);
    this.getVirtualData(this.currentYear);
    setTimeout(() => {
      this.drawChart(this.currentYear);
    }, 2000);
    // this.drawChart();
  }
  // 年份列表
  yearList: number[] = [];
  // 当前年份
  currentYear: number = 0;
  // 当前绘图
  myChart: any;
  // 图表展示的数据
  data: [string, number][] = [];
  maxValue: number = 100;

  // 1.绘图准备
  initChart() {
    var chartDom = document.getElementById("calendarHeatmap")!;
    // 初始化echarts实例，并设置主题
    this.myChart = echarts.init(chartDom, "macarons");
    // 设置加载动画
    this.myChart.showLoading();
  }
  // 初始化数据
  initData(year: number | string) {
    const date = +echarts.time.parse(year + "-01-01");
    const end = +echarts.time.parse(+year + "-12-31");
    const dayTime = 3600 * 24 * 1000;
    const data: [string, number][] = [];
    // 先将数据全部将初始化为0
    for (let time = date; time <= end; time += dayTime) {
      data.push([echarts.time.format(time, "{yyyy}-{MM}-{dd}", false), 0]);
    }
    this.data = data;
  }
  getVirtualData(year: number | string) {
    getEveryYearPublish(year.toString())
      .then((res) => {
        if (res.data.code === "200") {
          let resData = res.data.data;
          // 获取resData的最大值
          const values = Object.values(resData);
          this.maxValue = Math.max(...values as number[]);          
          const len = this.data.length;
          for (let i = 0; i < len; i++) {
            let tempData: string = this.data[i][0];
            this.data[i][1] = resData[tempData] || 0;
          }
          // 数据加载完成后，隐藏加载动画
          this.myChart.hideLoading();
        } else {
          this.$message.error("获取文章发布数据失败");
        }
      })
      .catch((error) => {
        setTimeout(() => {
          this.myChart.hideLoading();
        }, 3000);
        console.log(error);
      });
  }
  // 绘制图表
  drawChart(year: number) {
    var option: EChartsOption;
    option = {
      tooltip: {},
      visualMap: {
        show: true,
        min: 0,
        max: this.maxValue,
        type: "piecewise", //分段型
        orient: "horizontal", //水平
        left: "center",
        top: "bottom",
        inRange: {
          color: ["#ebedf0", "#c6e48b", "#7bc96f", "#239a3b", "#196127"],
        },
      },
      calendar: {
        top: "middle", //垂直居中
        right: 20, //水平居中
        cellSize: 16, //单元格大小
        yearLabel: {
          show: true,
        },
        dayLabel: {
          margin: 20,
          firstDay: 1,
          nameMap: "cn",
        },
        monthLabel: {
          show: true,
        },
        range: year,
      },
      series: {
        type: "heatmap",
        coordinateSystem: "calendar",
        // 日历图数据
        data: this.data,
        // 高亮样式
        emphasis: {
          // 鼠标悬浮时的样式
          itemStyle: {
            color: "skyBlue",
          },
        },
      },
    };
    // 短路求值，存在性检查
    option && this.myChart.setOption(option);
  }
  // 获取近三年的年份
  getYear() {
    let date = new Date();
    let year = date.getFullYear();
    var yearList: number[] = [];
    for (let i = 0; i < 3; i++) {
      yearList.push(year - i);
    }

    return yearList;
  }
  // 年份选择
  handleYearCommand(year: string) {
    this.currentYear = parseInt(year);
    // console.log(this.currentYear);
    // 设置加载动画
    this.myChart.showLoading();
    // 重新绘制图表
    // TODO:模拟
    this.drawChart(this.currentYear);

    // this.drawChart(this.currentYear);
  }
}
</script>

<style lang="scss" scoped>
</style>